﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Principal;

namespace Directory.Web
{
	/// <summary>
	/// CustomIdentity 的摘要说明
	/// </summary>
	public  sealed class CustomIdentity : IIdentity
	{
		private FormsAuthenticationTicket ticket;
		private HttpContext context = HttpContext.Current;

		public CustomIdentity(FormsAuthenticationTicket ticket)
		{
			this.ticket = ticket;
		}

		#region IIdentity 成员

		public string AuthenticationType
		{
			get { return "Custom"; }
		}

		public bool IsAuthenticated
		{
			get { return true; }
		}

		public string Name
		{
			get { return ticket.Name; }
		}

		#endregion

		public FormsAuthenticationTicket Ticket
		{
			get { return ticket; }
		}

		public string NickName
		{
			get
			{
				HttpCookie cookie = context.Request.Cookies[HttpContext.Current.Server.UrlEncode(this.Name + "_" + WebSettings.GetInstance().NickNameCookieKey)];

				if (cookie == null || string.IsNullOrEmpty(cookie.Value))
				{
					Directory.Model.UserInfo user = UserDataProxy.GetUserInfo(this.Name);
					if (string.IsNullOrEmpty(user.NickName))
					{
						cookie = new HttpCookie(HttpContext.Current.Server.UrlEncode(this.Name + "_" + WebSettings.GetInstance().NickNameCookieKey), HttpContext.Current.Server.UrlEncode(user.UserName));
					}
					else
					{
						cookie = new HttpCookie(HttpContext.Current.Server.UrlEncode(this.Name + "_" + WebSettings.GetInstance().NickNameCookieKey), HttpContext.Current.Server.UrlEncode(user.NickName));
					}
					cookie.Expires = DateTime.Now.AddMinutes(30);
					context.Response.Cookies.Add(cookie);
				}

				return HttpContext.Current.Server.UrlDecode(cookie.Value);
			}
		}

	}
}
